import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import {View, Block, Text, Image} from '@tarojs/components'
import {AtIcon} from 'taro-ui'
import {user} from '../../utils/user.service'
import {OrderDetail, TicketItem,} from '../../utils/server.interface'
import {http} from '../../utils/http'
import {
  GET_ORDER_DETAIL,
  GET_ORDER_TICKET,
  GET_ORDER_CHECKLOG,
  GET_TICKET_CODE,
  GET_IMG, RESOURCE_URL, BASE_URL
} from '../../constants/api'
import {getHeadTop, GetRequest, vcmonitor} from '../../utils/tools'
import {platform} from "../../utils/platform-settting.service";
import Headercar from "../components/header-car/header-car";
import {h5Wx} from "../../utils/h5.service";
import GzhAuth from "../../components/gzh-auth/gzh-auth"
import './detail.scss'

interface LogList {
  use_date: string
  check_num: number
  product_name: string
  company: string
}

export default class Detail extends Component {
  tabs = [{title: '套餐详情'}, {title: '验证码信息'}]
  state: {
    coupon: boolean
    searchBarTop: number
    orderInfo: OrderDetail | false
    orderTicket: TicketItem[]
    ticketwell: TicketItem[]
    ticketing: TicketItem[]
    ticketed: TicketItem[]
    logList: LogList[]
    refunding: boolean
    backRefund: boolean
    qrcodeimg: string
    pcodeimg: string
    tMore: boolean
    codeShow: boolean
    tabsIndex: number
    ticketWxCode: string
    ticketCode: string
    ticketName: string
    openGroup: boolean
    importText: string
    openAssembling: boolean
    wxCodeType: number
    popTicket: string
    groupTicket: any
    groupIndexs: any
    onlyTicketPay: any
    showNum: number
  } = {
    onlyTicketPay: '',
    coupon: false,
    searchBarTop: 0,
    pcodeimg: '',
    qrcodeimg: '',
    orderInfo: false,
    orderTicket: [],
    codeShow: false,
    ticketwell: [],
    ticketing: [],
    ticketed: [],
    logList: [],
    backRefund: true,
    refunding: false,
    tMore: false,
    ticketWxCode: '',
    wxCodeType: 0,
    ticketCode: '',
    ticketName: '',
    tabsIndex: 0,
    openGroup: false,
    importText: '',
    openAssembling: false,
    popTicket: '',
    groupTicket: [],
    groupIndexs: [],
    showNum: 3,
  }

  async componentDidShow() {
    vcmonitor(this)
  }

  async UNSAFE_componentWillMount() {
    if (process.env.TARO_ENV === 'h5') {
      await h5Wx.getConfig()
    }
    const headTop = getHeadTop()
    const searchBarTop = headTop.statusBar > 20 ? (headTop.statusBar + headTop.top + 30) : (headTop.statusBar + headTop.top + 40)
    this.setState({
      searchBarTop
    })
    const isLogin = await user.checkLogin()
    if (!isLogin) {
      Taro.showToast({
        title: '你还未登录，请登录',
        icon: 'none',
      })
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.switchTab({url: '/pages/my/index/index'})
      }, 1500)
      return
    }
    const {orderId, onlyTicketPay = ''} = Taro.getCurrentInstance().router.params
    if (!orderId) {
      Taro.showToast({title: '参数错误', icon: 'none'})
      const timer = setTimeout(() => {
        clearTimeout(timer)
        Taro.navigateBack({
          delta: 1
        })
      }, 1500);
    }
    Taro.showLoading({title: '加载中...'})
    const orderInfo = await http.get<OrderDetail>(GET_ORDER_DETAIL, {orderId})
    const orderTicket = await http.get<TicketItem[]>(GET_ORDER_TICKET, {orderId})
    const groupTicket = []
    const groupIndexs = []
    if (orderTicket) {
      if (orderTicket.length > 0) {
        const logList = await http.get<LogList[]>(GET_ORDER_CHECKLOG, {orderId})
        this.setState({logList})
        orderTicket.map((item) => {
          if (item.isUse == '已使用') {
            this.setState({
              backRefund: false
            })
          }
        })
      }
      if (orderTicket && orderTicket.length > 0) {
        orderTicket.map((item) => {
          groupTicket[item.group_index] = groupTicket[item.group_index] || {}
          groupTicket[item.group_index]['ticketwell'] = groupTicket[item.group_index]['ticketwell'] || []
          groupTicket[item.group_index]['ticketing'] = groupTicket[item.group_index]['ticketing'] || []
          groupTicket[item.group_index]['ticketed'] = groupTicket[item.group_index]['ticketed'] || []
          groupTicket[item.group_index]['tabsIndex'] = groupTicket[item.group_index]['tabsIndex'] || 0
          if (item.can_check_num && (item.is_use < 1 || item.is_use > 5)) {
            groupTicket[item.group_index]['ticketwell'].push(item)
          }
          if (item.used_check_num) {
            groupTicket[item.group_index]['ticketing'].push(item)
          }
          if (item.can_check_num && (item.is_use > 1 && item.is_use < 5)) {
            groupTicket[item.group_index]['ticketed'].push(item)
          }
          if (groupIndexs.indexOf(item.group_index) == -1) {
            groupIndexs.push(item.group_index)
          }
          if (groupTicket[item.group_index].ticketed.length > 0) {
            groupTicket[item.group_index]['tabsIndex'] = 2
          }
          if (groupTicket[item.group_index].ticketing.length > 0) {
            groupTicket[item.group_index]['tabsIndex'] = 1
          }
          if (groupTicket[item.group_index].ticketwell.length > 0) {
            groupTicket[item.group_index]['tabsIndex'] = 0
          }
        })
      }

    }
    this.setState({orderInfo, orderTicket, groupTicket, groupIndexs, onlyTicketPay})
    Taro.hideLoading()
  }

  checkTabs(tabsIndex, key) {
    const {groupTicket} = this.state
    groupTicket[key].tabsIndex = tabsIndex
    this.setState({groupTicket})
  }

  hideCode(e) {
    e.stopPropagation()
    this.setState({
      codeShow: false
    })
  }

  handleClickGroup() {
    const openGroup = this.state.openGroup
    this.setState({
      openGroup: !openGroup
    })
  }

  toggleMeals(showNum) {
    const {orderInfo} = this.state
    if (showNum == 3) {
      this.setState({showNum: orderInfo.meals.length})
    } else {
      this.setState({showNum: 3})
    }
  }

  async showCode(item) {
    if (this.state.onlyTicketPay === '1') {
      return false
    }
    const ret = await http.HGet(GET_TICKET_CODE, {ticketId: item.id})
    if (ret) {
      if (platform.info.checkStyleMini && platform.info.checkStyleMini > 0) {
        if (platform.info.checkStyleMini >= 1 && platform.info.checkStyleMini != 2) {
          this.setState({
            codeShow: true,
            ticketWxCode: ret.ticketWxCode,
            wxCodeType: item.type,
            popTicket: item.ticket,
            ticketName: item.product_name
          })
        }
        if (platform.info.checkStyleMini >= 2) {
          this.setState({
            codeShow: true,
            ticketCode: ret.ticketCode,
            wxCodeType: item.type,
            popTicket: item.ticket,
            ticketName: item.product_name
          })
        }
      }
    }
  }

  render() {
    const {ticketName, codeShow, searchBarTop, orderInfo, onlyTicketPay, groupTicket, popTicket, wxCodeType, ticketWxCode, ticketCode, showNum} = this.state
    if (!orderInfo) {
      return
    }
    return (
      <View className='meals-root'>
        <GzhAuth />
        {process.env.TARO_ENV !== 'tt' && !onlyTicketPay &&
        <View className='head-bg' style={`height: ${searchBarTop}Px;`}>
          <Headercar color='#333' title='套餐详情' />
        </View>}
        <View className='ticket-box-top'>
          <View className='ticket-wrapper'>
            <View className='order-info'>
              <Image className='img' src={orderInfo.default_img_url} mode='aspectFill' />
              <View className='name-box'>
                <View className='name'>{orderInfo.product_name}</View>
                {orderInfo.memo && <View className='valid-date'>{orderInfo.memo}</View>}
                <View className='date'>{orderInfo.add_date}</View>
              </View>
              <View className='order-info-right'>
                <View className='order-info-num'>x{orderInfo.buy_amount}</View>
                {orderInfo.pay_source_img && <Image className='order-info-from' src={orderInfo.pay_source_img} />}
              </View>
            </View>
          </View>
          <View className='good_meals_box'>
            <View className='meals-good'>
              <View className='Mtitle'>套餐包含({orderInfo.meals.length || 0})
                <View className='other-good-more'>{orderInfo.meal_type}</View>
              </View>
            </View>
            {orderInfo.meals.map((item, i) =>
              <Block>
                {i < showNum && <View key={i} className='good-item'>
                  <Text className='title'>{item.product_name}</Text>
                  <Text className='price'>x{item.buy_amount}</Text>
                </View>}
              </Block>)}
            {orderInfo.meals.length > 3 &&
            <View className='good_meals_more' onClick={this.toggleMeals.bind(this, showNum)}>{showNum > 3 ?
              <Block>收起<AtIcon value='chevron-up' size='15' color='#eb5a15' /></Block> :
              <Block>查看更多<AtIcon value='chevron-down' size='15' color='#eb5a15' /></Block>}</View>}
          </View>
          <View className='ticket-meals'>
            {groupTicket.map((val, key) => <View className={val.tabsIndex ? "ticket-top-info-d ticket-top-info" : "ticket-top-info"} key={key}>
              {(val.ticketing.length > 0 || val.ticketed.length > 0)
                ?
                <View className='qrbox'>
                  <View className='ticket-tabs'>
                    {val.ticketwell.length > 0 &&
                    <View className={val.tabsIndex == 0 ? 'ticket-tabs_item on' : 'ticket-tabs_item'}
                      onClick={this.checkTabs.bind(this, 0, key)}
                    >未使用</View>}
                    {val.ticketing.length > 0 &&
                    <View className={val.tabsIndex == 1 ? 'ticket-tabs_item on' : 'ticket-tabs_item'}
                      onClick={this.checkTabs.bind(this, 1, key)}
                    >已完成</View>}
                    {val.ticketed.length > 0 &&
                    <View className={val.tabsIndex == 2 ? 'ticket-tabs_item on' : 'ticket-tabs_item'}
                      onClick={this.checkTabs.bind(this, 2, key)}
                    >已过期</View>}
                  </View>
                  <View className='ticket-tabs-content'>
                    {val.tabsIndex == 0 && <Block>
                      {val.ticketwell.length == 0 ?
                        <View className='ticket_none'>
                          <Image src='https://resource.ivcheng.com/resources/images/meals_none.png'
                            mode='widthFix'
                          />
                          <View className='text'>没有可以使用的凭证</View>
                        </View>
                        :
                        <Block>
                          {val.ticketwell.map(item => <View className='ticket-box-well'
                            onClick={this.showCode.bind(this, item)} key={item.id}
                          >
                            <View className='ticket-well-num'>
                              <View className='ticket-well-num-box'>{item.product_name}</View>
                              {onlyTicketPay !== '1' && <View className='qr-code-image'><Image
                                src='https://resource.ivcheng.com/upload/images/20211004/1633338584052_434.png'
                                className='img'
                                mode='aspectFill'
                              /></View>}
                            </View>
                            <View className='ticket-well-num-line' />
                            <View className='ticket-well-state'>
                              <View>未使用</View>
                              <View className='ticket-time'>
                                {item.TicketMsg}
                              </View>
                              <View className='state'>{item.can_check_num}</View>
                            </View>
                          </View>)}
                        </Block>
                      }
                    </Block>}
                    {val.tabsIndex == 1 && val.ticketing.map(item => <View className='ticket-box-well' key={item.id}>
                      <View className='ticket-well-num'>
                        <View className='ticket-well-num-box'>{item.product_name}</View>
                      </View>
                      <View className='ticket-well-num-line' />
                      <View className='ticket-well-state'>
                        <View>已完成</View>
                        <View className='ticket-time'>
                          {item.TicketMsg}
                        </View>
                        <View className='state'>{item.used_check_num}</View>
                      </View>
                    </View>)}
                    {val.tabsIndex == 2 && val.ticketed.map(item => <View
                      className='ticket-box-well' key={item.id}
                    >
                      <View className='ticket-well-num'>
                        <View className='ticket-well-num-box'>{item.product_name}</View>
                      </View>
                      <View className='ticket-well-num-line' />
                      <View className='ticket-well-state'>
                        <View>已过期</View>
                        <View className='ticket-time'>
                          {item.TicketMsg}
                        </View>
                        <View className='state'>{item.can_check_num}</View>
                      </View>
                    </View>)}
                  </View>
                </View>
                :
                <View className='qrbox'>
                  {val.ticketwell.length == 0 ?
                    <View className='ticket_none'>
                      <Image src='https://resource.ivcheng.com/resources/images/meals_none.png'
                        mode='widthFix'
                      />
                      <View className='text'>没有可以使用的凭证</View>
                    </View>
                    :
                    <Block>
                      {val.ticketwell.map(item => <View className='ticket-box-well'
                        onClick={this.showCode.bind(this, item)} key={item.id}
                      >
                        <View className='ticket-well-num'>
                          <View className='ticket-well-num-box'>{item.product_name}</View>
                          {item.type != 2 && onlyTicketPay !== '1' && <View className='qr-code-image'><Image
                            src='https://resource.ivcheng.com/upload/images/20211004/1633338584052_434.png'
                            className='img'
                            mode='aspectFill'
                          /></View>}
                        </View>
                        <View className='ticket-well-num-line' />
                        <View className='ticket-well-state'>
                          <View>未使用</View>
                          <View className='ticket-time'>
                            {item.TicketMsg}
                          </View>
                          <View className='state'>{item.can_check_num}</View>
                        </View>
                      </View>)}
                    </Block>
                  }
                </View>
              }
            </View>)}
          </View>
        </View>
        {codeShow && <View className='show_code'>
          <View className='show_code_bj' onClick={this.hideCode.bind(this)} />
          <View className='show_code_content'>
            <View className='show_code_title'>{ticketName}</View>
            <View className='show_code_box'>
              {ticketWxCode && wxCodeType != 2 &&
              <View className='ticketWxCode'><Image className='img' src={ticketWxCode} /></View>}{ticketCode &&
            <View className='ticketCode'><Image className='img' src={BASE_URL + GET_IMG + ticketCode} /></View>}
            </View>
            <View className='show_code_tips'>
              {popTicket && <View className='show_code_ticket'>核验码：{popTicket}</View>}
              <View className='show_code_title'>出示该二维码即可消费该套餐</View>
              <View className='show_code_desc'>避免商家网络不佳影响使用，建议截图保存
                在相册</View>
            </View>
            <Image className='close' src={RESOURCE_URL + "/resources/weapp/images/codeOff.png"}
              onClick={this.hideCode.bind(this)}
            />
          </View>
        </View>}
      </View>
    )
  }
}
